
from google.appengine.ext import db
from google.appengine.api import memcache
import settings

class setting(db.Model):
    name = db.StringProperty(required=True, indexed=True)
    value = db.TextProperty()
    
    @staticmethod
    def get(key):
        value = memcache.get(key, settings.CACHE_NS_SETTING)
        if value is not None:
            return value
        else:
            q = setting.all().filter("name =", key).get()
            if q is not None:
                value = q.value
                memcache.set(key, value, settings.CACHE_DURATION_SETTING)
        return value               
    
    @staticmethod
    def set(key, value):
        q = setting.all().filter("name =", key).get()
        if q is None:
            q = setting(name = key)
        q.value = value
        q.put()
        memcache.delete(key, namespace = settings.CACHE_NS_SETTING)
        memcache.set(key, value, settings.CACHE_DURATION_SETTING) 
          
class Chain(db.Model):
    name = db.StringProperty(required=True)
    title = db.StringProperty()
    logo = db.LinkProperty()
    desc = db.TextProperty() 
    link = db.LinkProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
class Shop(db.Model):
    name = db.StringProperty(required=True)
    address = db.StringProperty()
    telephone = db.StringListProperty()
    id_dianping = db.IntegerProperty()
    id_sodexo = db.IntegerProperty()
    ischain = db.BooleanProperty(default=False)
    chainname = db.StringProperty()
    chain = db.ReferenceProperty(Chain)
    location = db.GeoPtProperty()
    tags = db.StringListProperty()
    gmaped = db.BooleanProperty(default=False)
    related = db.StringListProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    
    @staticmethod
    def add_shop(id_sodexo, name, address, telephone = None, tags = [], related=[]):
        if id_sodexo is None: return None
        key = str(id_sodexo)
        s = Shop.get_or_insert(key, id_sodexo=int(id_sodexo), name = name, address = address)
        phone = []
        if telephone is not None:
            items = telephone.split(',')
            for item in items:
                phone.append(item)
        s.telephone = phone
        s.tags = tags
        s.related = related
        s.put()
        return s
    
    @staticmethod
    def get_shop(id_sodexo):
        if id_sodexo is None: return None
        return Shop.all().filter("id_sodexo =", int(id_sodexo)).get()
    
    def assign_location(self, lat, lng):
        self.location = db.GeoPt(lat=float(lat), lon=float(lng))
        self.put()
        return self
            
                
            
        
    

        